#-*- coding:utf-8 -*-
import time

from runtime.pkg.views import get_pkg
from runtime.utils.msg_tools import get_msg_key, get_msg
from runtime.utils.event_handler import Event

import autoreply


def midware(request):
	msg_get = get_msg(request)
	if msg_get.MsgType.text == 'event':
		event = Event(request)
		msg_reply = msg_response(msg_get, event.handler())
	else:
		msg_reply = msg_filter(request)
	return msg_reply


def msg_filter(request):
	msg_get = get_msg(request)
	msg_key = get_msg_key(msg_get)
	pkg_name = get_pkg(msg_key)

	if pkg_name == 'runtime.users':
		from runtime.users.views import run
		msg_content = run(request)
		
	elif pkg_name:
		pkg_name += '.views'
		try:
			pkg_object = __import__(pkg_name, fromlist=['run'])
			msg_content = pkg_object.run(request)
		except AttributeError:
			msg_content = {
				'msg_type': 'text',
				'content': 'AttributeError',
			}
	else:
		msg_content = autoreply.views.run(request)

	return msg_response(msg_get, msg_content)

def msg_response(msg_get, msg_content):
	to_user = msg_get.FromUserName.text
	from_user = msg_get.ToUserName.text
	create_time = int(time.time())
	msg_head = {
		'to_user': to_user,
		'from_user': from_user,
		'create_time': create_time,
	}
	msg_content.update(msg_head)

	return msg_content